#include "videowidget.h"
extern "C"
{
#include "libavutil/mem.h"
}
#include <QPainter>
videowidget::videowidget(QWidget *parent)
    : QWidget{parent}
{
    setAttribute(Qt::WA_StyledBackground);
    setStyleSheet("background: black");
    m_img         = NULL;
    m_serial      = 0;
    m_rect_serial = 0;
}
videowidget::~videowidget()
{
    freeImage();
}

int videowidget::serial() const
{
    return m_serial;
}

void videowidget::setSerial(int newSerial)
{
    m_serial = newSerial;
}
void videowidget::paintEvent(QPaintEvent *event)
{
    if(!m_img)
        return;
    if(m_rect_serial != m_serial)
        return;
    QPainter(this).drawImage(m_rect, *m_img);
}

void videowidget::freeImage()
{
    if(m_img)
    {
        av_free(m_buffer);
        delete m_img;
        m_img = nullptr;
    }
}

void videowidget::showImage(uint8_t* data, int width, int height)
{
    freeImage();
    m_buffer = data;
    m_img = new QImage(m_buffer, width, height, QImage::Format_RGB888);
    if(m_img)
    {
        int w=this->width();
        int h=this->height();

        // 计算rect
        int dx=0;
        int dy=0;
        int dw=m_img->width();
        int dh=m_img->height();

        if (dw>w||dh>h) { // 缩放
            if (dw*h>w*dh) { // 视频的宽高比 > 播放器的宽高比
                dh=w*dh/dw;
                dw=w;
            } else {
                dw=h*dw/dh;
                dh=h;
            }
        }
        dx=(w - dw) >> 1;
        dy=(h - dh) >> 1;
        m_rect=QRect(dx, dy, dw, dh);
        m_rect_serial = m_serial;
    }
    update();
}
